package com.daqsoft.controller.project;

import com.daqsoft.data.User;
import com.daqsoft.data.project.Attachment;
import com.daqsoft.data.project.Project;
import com.daqsoft.dto.GeneralResultEnum;
import com.daqsoft.dto.StatusEnum;
import com.daqsoft.permission.Verify;
import com.daqsoft.permission.VerifyType;
import com.daqsoft.service.project.ProjectService;
import com.daqsoft.service.system.PDFService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 项目管理控制器
 * @author 周麟东 on 10:13
 */
@RestController
@RequestMapping("project")
@Verify(desc = "项目管理")
public class ProjectController {

    Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ProjectService service;
    @Value("${file.dir}")
    private String fileDir;

    @RequestMapping("save")
    @Verify(value = VerifyType.HAVE_PERMISSION , desc = "保存项目")
    public GeneralResultEnum saveProject(HttpServletRequest request , int pmUserId , Project project){
        User user = (User) request.getSession().getAttribute("user");
        project.setCreator(user);
        return GeneralResultEnum.SUCCESS.setData(service.save(project , pmUserId).toMap()).setDesc("保存项目成功");
    }

    @RequestMapping("remove")
    @Verify(value = VerifyType.HAVE_PERMISSION , desc = "删除项目")
    public GeneralResultEnum removeProject(int id){
        service.delete(id);
        return GeneralResultEnum.SUCCESS.setDesc("删除项目成功!");
    }
    @RequestMapping("get")
    @Verify(value = VerifyType.HAVE_PERMISSION , desc = "通过ID获取项目")
    public GeneralResultEnum get(int id){
        return GeneralResultEnum.SUCCESS.setData(service.get(id).toMap()).setDesc("获取成功");
    }
    @RequestMapping("getByStatus")
    @Verify(value = VerifyType.HAVE_PERMISSION,desc = "通过状态获取所有项目")
    public GeneralResultEnum getByStatus(String status){
        List<Project> projects = service.getByStatus(StatusEnum.valueOf(status));
        List<Map<String,Object>> list = new ArrayList<>();
        for (Project project : projects) {
            list.add(project.toMap());
        }
        return GeneralResultEnum.SUCCESS.setData(list);
    }

    @RequestMapping("getAllSimpleProject")
    @Verify(value = VerifyType.HAVE_PERMISSION,desc = "获取简单结构的项目信息")
    public GeneralResultEnum getAllSimpleProject(HttpServletRequest request){
        User user = (User) request.getSession().getAttribute("user");
        List<Project> projects = service.getAll();
        List<Map<String,Object>> list = new ArrayList<>();
        for (Project project : projects) {
            list.add(project.toSimpleMap(user));
        }
        return GeneralResultEnum.SUCCESS.setData(list);
    }

    @RequestMapping("projectInfoCompar")
    @Verify(value = VerifyType.HAVE_PERMISSION,desc = "获取两个项目的基本信息比较")
    public GeneralResultEnum projectInfoCompar(int projectA , int projectB){
        if (projectA == projectB){
            return GeneralResultEnum.FAIL.setDesc("项目比较失败 , 两个项目ID都为:"+ projectA);
        }
        Project p1 = service.get(projectA);
        if (p1 == null){
            return GeneralResultEnum.FAIL.setDesc("项目A 不存在 id = "+ projectA);
        }
        Project p2 = service.get(projectB);
        if (p2 == null){
            return GeneralResultEnum.FAIL.setDesc("项目B 不存在 id = "+ projectB);
        }
        return GeneralResultEnum.SUCCESS.setData(service.projectInfoCompar(p1 , p2)).setDesc("获取项目基本信息比较成功");
    }
    @RequestMapping("projectPlanCompar")
    @Verify(value = VerifyType.HAVE_PERMISSION,desc = "获取两个项目的计划信息比较")
    public GeneralResultEnum projectPlanCompar(int projectA , int projectB){
        if (projectA == 0 || projectB == 0){
            return GeneralResultEnum.SUCCESS;
        }
        if (projectA == projectB){
            return GeneralResultEnum.FAIL.setDesc("项目比较失败 , 两个项目ID都为:"+ projectA);
        }
        Project p1 = service.get(projectA);
        if (p1 == null){
            return GeneralResultEnum.FAIL.setDesc("项目A 不存在 id = "+ projectA);
        }
        Project p2 = service.get(projectB);
        if (p2 == null){
            return GeneralResultEnum.FAIL.setDesc("项目B 不存在 id = "+ projectB);
        }
        return GeneralResultEnum.SUCCESS.setChildren(service.projectPlanCompar(p1 , p2)).setDesc("获取项目计划信息比较成功");
    }

    @RequestMapping("downloadProject")
    @Verify(VerifyType.HAVE_PERMISSION)
    public void getProjectByPDF(HttpServletResponse response , int projectId){
        Project project = service.get(projectId);
        BufferedInputStream bis = null;
        try {
            response.addHeader("Content-Disposition",
                    "attachment;filename=\""
                            + new String((project.getProjectName()+"简介.pdf")
                            .getBytes("GBK"), "ISO8859_1") + "\"");
            OutputStream os = response.getOutputStream();
            byte[] buff = new byte[1024];
            File file =  new File(fileDir+File.separator+"doc"+File.separator+"project_out_doc_"+projectId+".pdf");
            log.info(file.getAbsolutePath());
            if(!file.exists()){
                //创建文件
                log.info("找不到id={}创建PDF",projectId);
                service.createPDF(project);
            }
            bis = new BufferedInputStream(new FileInputStream(file));
            int i = bis.read(buff);
            while (i != -1) {
                os.write(buff, 0, buff.length);
                os.flush();
                i = bis.read(buff);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
